package cn.com.youjile.listener;

import cn.com.youjile.client.GeneralClient;
import cn.com.youjile.config.InitConfig;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.EventLoop;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * @Author youjile
 * @CreateDate 2021/3/12
 * @Describe 与server断开连接后，从新连接
 */
public class ConnListener implements ChannelFutureListener {

    public static int connCount = InitConfig.connCountTotal;       //连接次数,计数器


    private static final Logger logger = LoggerFactory.getLogger(ConnListener.class);

    @Override
    public void operationComplete(ChannelFuture channelFuture) {
        try {
            if (!channelFuture.isSuccess()) {
                final EventLoop loop = channelFuture.channel().eventLoop();
                loop.schedule(new Runnable() {
                    @Override
                    public void run() {
                        if(connCount < 0) {
                            logger.error("client重连 server 100次都未成功，直接关闭当前程序");
                            //System.exit(-1);    //重连200次都未成功，直接关闭当前程序
                        }
                        logger.error("服务端链接不上，开始重连操作...");
                        try {
                            new GeneralClient(InitConfig.host, InitConfig.clientPort).run();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        connCount--;
                    }
                }, 3, TimeUnit.SECONDS);
            } else {
                logger.info("服务端链接成功...");
            }
        } catch (Exception e) {
            logger.error("服务端链接不上...");
            e.printStackTrace();
        }
    }

    public static void resetConnCount(){
        connCount = InitConfig.connCountTotal;
    }
}
